package com.tianji.learning.task;

import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.DateUtils;
import com.tianji.learning.constants.RedisConstants;
import com.tianji.learning.domain.po.PointsBoard;
import com.tianji.learning.domain.po.PointsBoardSeason;
import com.tianji.learning.service.IPointsBoardSeasonService;
import com.tianji.learning.service.IPointsBoardService;
import com.tianji.learning.utils.TableInfoContext;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.tianji.learning.constants.LearningConstants.POINTS_BOARD_TABLE_PREFIX;

/**
 * @Description 创建上赛季 榜单表
 * @Author lyx
 * @since 2025/2/6 15:42
 */

@Component
@RequiredArgsConstructor
@Slf4j
public class PointsBoardPersistentHandler {

    private final IPointsBoardSeasonService pointsBoardSeasonService;

    private final IPointsBoardService pointsBoardService;
    private final StringRedisTemplate redisTemplate;

    //@Scheduled(cron = "0 0 3 1 * ?") // 每月1号，凌晨3点执行
    @XxlJob("createTableJob")
    public void createPointsBoardTableOfLastSeason(){
        log.debug("创建上赛季榜单表任务执行了");
        // 1.获取上月时间
        LocalDate time = LocalDate.now().minusMonths(1);

        //2.查询赛季id
        PointsBoardSeason one = pointsBoardSeasonService.lambdaQuery()
                .le(PointsBoardSeason::getBeginTime, time)
                .ge(PointsBoardSeason::getEndTime, time)
                .one();
        log.debug("上赛季信息 {}", one);
        if (one == null){
            return;
        }

        // 3.创建表
        pointsBoardSeasonService.createPointsBoardLatestTable(one.getId());
    }

    /**
     * 持久化上赛季排行榜数据 到db中
     */
    @XxlJob("savePointsBoard2DB")
    public void savePointsBoard2DB(){
        // 1.获取上月时间
        LocalDateTime time = LocalDateTime.now().minusMonths(1);

        //2.查询赛季表 获取上赛季信息
        PointsBoardSeason one = pointsBoardSeasonService.lambdaQuery()
                .le(PointsBoardSeason::getBeginTime, time)
                .ge(PointsBoardSeason::getEndTime, time)
                .one();
        log.debug("上赛季信息 {}", one);
        if (one == null){
            return;
        }

        //3.计算动态表名 并存入threadlocal
        String tableName = POINTS_BOARD_TABLE_PREFIX + one.getId();
        log.debug("动态表名为{}",tableName);
        TableInfoContext.setInfo(tableName);

        //4.获取上赛季积分排行榜数据 分页
        String format = time.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + format; //board：上赛季年月

        int index = XxlJobHelper.getShardIndex();//当前分片的索引，从0开始
        int total = XxlJobHelper.getShardTotal();//总分片数

        int pageNo = index + 1; // 起始页，就是分片序号+1
        int pageSize = 1000; //条数
        while (true){
            List<PointsBoard> pointsBoardList = pointsBoardService.queryCurrentBoardList(key, pageNo, pageSize);
            if (CollUtils.isEmpty(pointsBoardList)){
                break;
            }
            //翻页，跳过N个页，N就是分片数量
            pageNo+=total;

            //5.持久化到db相应的赛季表中  批量新增
            for (PointsBoard board : pointsBoardList) {
                board.setId(Long.valueOf(board.getRank())); //历史排行榜的id 就代表排名
                board.setRank(null);//清空数据
            }
            pointsBoardService.saveBatch(pointsBoardList);
        }

        //6.清空threadlocal中数据
        TableInfoContext.remove();
    }

    @XxlJob("clearPointsBoardFromRedis")
    public void clearPointsBoardFromRedis(){
        // 1.获取上月时间
        LocalDateTime time = LocalDateTime.now().minusMonths(1);
        // 2.计算key
        String format = time.format(DateTimeFormatter.ofPattern("yyyyMM"));
        String key = RedisConstants.POINTS_BOARD_KEY_PREFIX + format; //board：上赛季年月
        // 3.删除
        redisTemplate.unlink(key);
    }
}
